package com.ft.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ft.dao.*;
import com.ft.domain.Answer;
import com.ft.domain.StudyAnswer;
import com.ft.service.IStudyAnswerService;
import com.ft.utils.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: ft
 * @Date: 2023/01/12/12:31
 * @Description:
 */
@Service
public class StudyAnswerServiceImpl extends ServiceImpl<StudyAnswerDao, StudyAnswer> implements IStudyAnswerService {
    @Autowired
    private StudyAnswerDao answerDao;
    @Autowired
    private StudyFistcommentDao fistcommentDao;
    @Autowired
    private StudyDao studyDao;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 创建回复信息表
     * @param answer
     * @return
     */
    @Override
    public int addStudyAnswer(StudyAnswer answer,String num) throws IllegalAccessException {
        String AnsweridList = fistcommentDao.getAnswerIdlist (answer.getBelongtofistcomment ());
        if(AnsweridList.length () > 0 & AnsweridList != ""){
            AnsweridList = AnsweridList +answer.getId ()+",";
        }else {
            AnsweridList = answer.getId ()+",";
        }
        //增加回复
        int i = answerDao.addAnswer (answer);
        //更新一级评论回复id
        int j = fistcommentDao.addAnswerIdlist (AnsweridList,answer.getBelongtofistcomment ());
        //获取一级评论所属帖子id
        Long postId = fistcommentDao.getStudyId(answer.getBelongtofistcomment ());
        //获取帖子所有回复数量
        int commentnum = studyDao.getCommentnum (postId);
        //更新帖子的所有回复数
        int h = studyDao.updataCommentnum (commentnum+1, postId);
        if(i == 1 & j == 1 & h == 1){
            //1.将帖子id存入缓存
            String id = String.valueOf (answer.getId ());
            redisTemplate.opsForZSet().add("studyanswerId",id,0);
            //将帖子信息存入缓存
            String postKey1 = "studyanswer:"+answer.getId ();
            Map<String, Object> stringObjectMap = ObjectUtils.objectToMap (answer);
            redisTemplate.opsForHash ().putAll (postKey1, stringObjectMap);
            //同步回复创建时间
            redisTemplate.opsForHash().delete(postKey1,"createTime");
            String time = answerDao.getcreateTime(answer.getId ());
            redisTemplate.opsForHash().put(postKey1,"createTime",time);
            //检查是数据否添加成功
            Long  hashOrderSize = redisTemplate.opsForHash().size (postKey1);
            while (true){
                //结束条件,验证每个字段是否都添加上了
                if(hashOrderSize == StudyAnswer.total){
                    break;
                }
                if(hashOrderSize != StudyAnswer.total){
                    //移除key
                    redisTemplate.delete (postKey1);
                    //重新添加
                    Map<String, Object> stringObjectMap1 = ObjectUtils.objectToMap (answer);
                    Set mapkey1 = stringObjectMap1.keySet ();
                    for(Object key : mapkey1){
                        redisTemplate.opsForHash().put(postKey1,key,stringObjectMap.get (key));
                    }
                }
            }
            //更新redis中的帖子评论id缓存字段
            //修改redis中对应字段
            redisTemplate.opsForHash().put("studyfistcomment:"+answer.getBelongtofistcomment (),"answerIdlist",AnsweridList);
            //更新帖子回复数
            redisTemplate.opsForHash().put("study:"+postId,"commentnum",commentnum+1);
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * 更加评论id获取回复消息
     * @param answerIdlist
     * @return
     */
    @Override
    public List<StudyAnswer> getfistcommentsByPostId(String answerIdlist) {
        List list = new ArrayList ();
        String[] answerlist = answerIdlist.split (",");
        for(int j = 0; j < answerlist.length; j++){
            //获取对应的answer数据
            Answer answer = new Answer ();
            Map entries = redisTemplate.opsForHash ().entries ("studyanswer:" + answerlist[j]);
            answer.setId ((Long) entries.get("id"));
            answer.setBelongtofistcomment ((Long) entries.get("belongtofistcomment"));
            answer.setAnswerContent ((String) entries.get("answerContent"));
            answer.setCreateTime (Timestamp.valueOf((String) entries.get("createTime")));
            answer.setState ((Integer) entries.get("state"));
            answer.setAnswerTouserid ((Integer) entries.get("answerTouserid"));
            answer.setAnswerUserid ((Integer) entries.get("answerUserid"));
            answer.setAnswerUsername ((String)entries.get("answerUsername"));
            answer.setAnswerTousername ((String) entries.get("answerTousername"));
            list.add(answer);
        }
        return list;
    }

    @Override
    public String getCreateTime(Long id) {
        String time = answerDao.getcreateTime (id);
        return time;
    }

    /**
     * 更加id删除单个回复记录
     * @param id
     * @return
     */
    @Override
    public int deleteStudyAnswer(Long id) {
        //获取该回复id所属评论id
        Long belongFistcomment = answerDao.getBelongFistcomment(id);
        int i = answerDao.deleteAnswer (id);
        if(i == 1){
            //删除redis中回复hash对应数据
            System.out.println ("0");
            Boolean delete = redisTemplate.delete ("studyanswer:"+id);
            System.out.println ("1");
            //删除回复zet中对应id
            redisTemplate.boundZSetOps("studyanswerId").remove(""+id);
            System.out.println ("2");
            //获取评论表里的用户回复id字段
            String answerIdlist = fistcommentDao.getAnswerIdlist(belongFistcomment);
            String T = "";
            //将用户回复id字段转换成数组
            if(! "".equals (answerIdlist) | answerIdlist.length () > 0) {
                String[] answerlist = answerIdlist.split (",");
                //取出对应回复id字段
                for (int j = 0; j < answerlist.length; j++) {
                    if (answerlist[j].equals ("" + id)) {
                        continue;
                    } else {
                        T += answerlist[j] + ",";
                    }
                }
            }
            //将用户回复id集合存入评论表中
            int i1 = fistcommentDao.addAnswerIdlist (T,belongFistcomment);
            //获取评论所属帖子id
            Long studyId = fistcommentDao.getStudyId (belongFistcomment);
            //获取帖子回复数量
            int commentnum = studyDao.getCommentnum (studyId);
            //更新帖子回复量
            int h = studyDao.updataCommentnum (commentnum-1, studyId);
            if(i1 == 1 & h == 1){
                //修改redis中对应字段
                //更新redis中评论表的用户回复id集合字段
                redisTemplate.opsForHash().put("studyfistcomment:"+belongFistcomment,"answerIdlist",T);
                //更新帖子回复数
                redisTemplate.opsForHash().put("study:"+studyId,"commentnum",commentnum-1);
            }else {
                return 0;
            }
            return 1;
        }
        return 0;
    }

    /**
     * 更加id删除多个回复记录
     * @param array
     * @return
     */
    @Override
    public int deleteAnswerArray(String[] array,Long belongFistcomment) {
        //获取要删除的元素个数
        int num = array.length ;
        //获取所属评论的帖子id
        Long studyId = fistcommentDao.getStudyId (belongFistcomment);
        int i = answerDao.deleteAnswerArray (array);
        //将用户回复id集合存入评论表中
        int i1 = fistcommentDao.addAnswerIdlist ("",belongFistcomment);
        //获取帖子回复数量
        int commentnum = studyDao.getCommentnum (studyId);
        //更新帖子回复量
        int h = studyDao.updataCommentnum (commentnum-num, studyId);
        //删除成功的情况
        if(i == num & i1 == 1 ){
            //更新缓存数据
            for (int j = 0; j < array.length; j++) {
                redisTemplate.delete ("studyanswer:"+array[j]);
                //删除回复zet中对应id
                redisTemplate.boundZSetOps("studyanswerId").remove(""+array[j]);
                //更新redis中评论表的用户回复id集合字段
                redisTemplate.opsForHash().put("studyfistcomment:"+belongFistcomment,"answerIdlist","");
                //更新帖子回复数
                redisTemplate.opsForHash().put("study:"+studyId,"commentnum",commentnum-num);
            }
            return 1;
        }
        return 0;
    }
}
